//
//  DataEyeSDKHelper.m
//  UnityFramework
//

#import <Foundation/Foundation.h>
#import "DataEyeSDK/DataEyeSDK.h"
#import "DataEyeSDKHelper.h"

@implementation DataEyeSDKHelper

+ (instancetype)sharedInstance {
    static DataEyeSDKHelper *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)initializeDataEyes {
    NSString *appId = @"13311";
    NSString *url = @"https://bct.nicolegames.com";
    
    DataEyeSDK *instance = [DataEyeSDK startWithAppId:appId withUrl:url];
    
    if (!instance) {
        NSLog(@"DataEyeSDK initialization failed");
        return;
    }
    
    [[DataEyeSDK sharedInstance] enableAutoTrack:
         DataEyeEventTypeAppStart |
         DataEyeEventTypeAppEnd |
         DataEyeEventTypeAppViewScreen |
         DataEyeEventTypeAppClick |
         DataEyeEventTypeAppInstall |
         DataEyeEventTypeAppViewCrash
    ];
    
    NSLog(@"DataEyeSDK initialized successfully");
}

-(void)sendBILog:(NSString *)key value:(NSString *)value {
  NSError *jsonError;
  NSDictionary *eventProperties = nil;

  NSLog(@"DataEyeSDK 接收到数据 - Key: %@, Value: %@, Value长度: %lu", key, value, (unsigned long)value.length);

  if (value && value.length > 0) {
    NSData *jsonData = [value dataUsingEncoding:NSUTF8StringEncoding];

    eventProperties = [NSJSONSerialization JSONObjectWithData:jsonData
                            options:NSJSONReadingMutableContainers
                             error:&jsonError];

    if (jsonError || !eventProperties) {
      // 处理 JSON 解析错误或 eventProperties 为 nil 的情况
      NSLog(@"JSON 解析错误: %@", jsonError);
      eventProperties = @{};  // 使用空字典替代
    }
  }

  NSLog(@"发送BI: Key%@, Value: %@, Value长度: %lu", key, value, (unsigned long)value.length);
  [[DataEyeSDK sharedInstance] track:key properties:eventProperties];
}

-(void)sendUserSet:(NSString *) value {
  NSLog(@"用户属性打点===>%@", value);

  NSData *jsonData = [value dataUsingEncoding:NSUTF8StringEncoding];
  NSError *edro;
  id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&edro];
  NSDictionary *eventProperties = jsonObject;

  [[DataEyeSDK sharedInstance]user_set:eventProperties ];
}
@end
